#include "App_mqtt.h"

static MQTTClient client;
static MQTTClient_connectOptions conn_opts = MQTTClient_connectOptions_initializer;
// 接收消息回调函数
static int (*recv_callback)(char *json) = NULL;
static MQTTClient_message pubmsg = MQTTClient_message_initializer;

// 发送消息完成的回调函数
static void delivered(void *context, MQTTClient_deliveryToken dt)
{
    log_debug("消息发送完成");
}

// 接收到远程消息的回调函数
// 此函数的返回值为1代表成功处理， 为0代表处理失败
static int msgarrvd(void *context, char *topicName, int topicLen, MQTTClient_message *message)
{
    log_debug("接收消息");
    log_debug("topic: %s\n", topicName);
    log_debug("message: %.*s\n", message->payloadlen, (char *)message->payload);
    int result = 0;
    if (recv_callback)
    {
        // 调用注册的回调函数处理消息
        result = (recv_callback(message->payload) == 0 ? 1 : 0); // 处理成功返回1，处理失败返回0
    }
    MQTTClient_freeMessage(&message);
    MQTTClient_free(topicName);
    return result;
}

// 连接断开回调函数
static void connlost(void *context, char *cause)
{
    log_debug("连接断开");
    log_debug("原因: %s\n", cause);
}

int App_mqtt_Init(void)
{
    // 1.创建MQTT客户端
    if (MQTTClient_create(&client, ADDRESS, CLIENTID, MQTTCLIENT_PERSISTENCE_NONE, NULL) != MQTTCLIENT_SUCCESS)
    {
        log_debug("MQTT客户端创建失败");
        return -1;
    }

    // 2.设置回调函数
    if (MQTTClient_setCallbacks(client, NULL, connlost, msgarrvd, delivered) != MQTTCLIENT_SUCCESS)
    {
        log_debug("MQTT回调函数设置失败");
        MQTTClient_destroy(&client);
        return -1;
    }

    // 3.连接MQTT服务器
    if (MQTTClient_connect(client, &conn_opts) != MQTTCLIENT_SUCCESS)
    {
        log_debug("连接MQTT服务器失败");
        MQTTClient_destroy(&client);
        return -1;
    }

    // 4.订阅主题
    if (MQTTClient_subscribe(client, TOPIC_RTG, QOS) != MQTTCLIENT_SUCCESS)
    {
        log_debug("订阅主题失败");
        MQTTClient_disconnect(client, TIMEOUT);
        MQTTClient_destroy(&client);
        return -1;
    }
    log_debug("mqtt初始化成功");

    return 0;
}

void App_mqtt_Close(void)
{
    MQTTClient_unsubscribe(client, TOPIC_RTG);
    MQTTClient_disconnect(client, TIMEOUT);
    MQTTClient_destroy(&client);
}

int App_mqtt_Send(char *json)
{
    pubmsg.payload = json;
    pubmsg.payloadlen = (int)strlen(json);
    pubmsg.qos = QOS;
    if (MQTTClient_publishMessage(client, TOPIC_GTR, &pubmsg, NULL) != MQTTCLIENT_SUCCESS)
    {
        log_error("发送消息失败");
        return -1;
    }
    return 0;
}

void App_mqtt_RegisterRecvCallback(int (*callback)(char *json))
{
    recv_callback = callback;
}
